﻿
#include "list.h"
#include <stdio.h> 
#include <stdlib.h>
bool IsEmpty(Node* head){
	if(head==0){//empty list
		return true;
	}else{
		return false;
	}
}

Node* InsertNode(Node** phead, int index, double x){
	if(index<0)return 0;//invalid index

	//start from head
	int currIndex=1;
	Node* currNode=*phead;

	while(currNode&&index>currIndex){
		currNode=currNode->next;
		currIndex++;
	}//not match, move to next node

	if(index>0&&currNode==0)return 0;//no match

	//create new node
	Node* newNode=(Node*)malloc(sizeof(Node));
	newNode->data=x;
	if(index==0){//insert in the front or empty list
		newNode->next=*phead;
		*phead=newNode;
	}else{//insert in the middle or end
		newNode->next=currNode->next;
		currNode->next=newNode;
	}
	return newNode;
}

int FindNode(Node* head, double x){

	//start from head
	int currIndex=1;
	Node* currNode=head;

	while(currNode){
		if(currNode->data==x){
			return currIndex;//matched
			break;
		}
		currNode=currNode->next;
		currIndex++;
	}//not match, move to next node	
	return 0;//no match
}

int DeleteNode(Node** phead, double x){
    //start from head
	int currIndex=1;
	Node* currNode=*phead;
	Node* prevNode=0;

	while(currNode){
		if(currNode->data==x){//matched
			if(prevNode==0){//first node
				*phead=currNode->next;
			}else{//not first node
				prevNode->next=currNode->next;
			}
			free(currNode);//free memory
			return currIndex;
		}
		prevNode=currNode;
		currNode=currNode->next;
		currIndex++;
	}//not match, move to next node	
	return 0;//no match
}

void DisplayList(Node* head){
	printf("*******Display List********\n");
    //start from head
	Node* currNode=head;

	while(currNode){
		printf("%.2f\t",currNode->data);
		currNode=currNode->next;
	}
	printf("\n********End********\n");
}

void DestroyList(Node** phead){
    //start from head
	Node* currNode=*phead;

	while(currNode){
		Node* thisNode=currNode;
        currNode=currNode->next;
		free(thisNode);
	}//free each node

	*phead=0;//set list to null
}

int main(void)
{
	Node *head = 0;
	for(int i=0; i<5; i++)
		InsertNode(&head, i, i);
	DisplayList(head);
	
    for(int i=0; i<5; i++)
		InsertNode(&head, 0, i);
	DisplayList(head);
    
    InsertNode(&head,12, 7);
    DisplayList(head);

	for(int i=0; i<7; i+=2){
		int idx = FindNode(head, i);
		if(idx>0)
			printf("%d is at position %d.\n", i, idx);
		else
			printf("%d is not in the list.\n", i);
	}
	DeleteNode(&head, 0);
	DisplayList(head);

	DeleteNode(&head,4);
	DisplayList(head);

    DeleteNode(&head, 7);
    DisplayList(head);
	
    DestroyList(&head);
	DisplayList(head);

	return 0;
}
